<template>
  <div class="home">
    <a-button type="primary" @click="applyTest" class="applyTest">申请试用</a-button>
    <div class="main">
      <img src="@\assets\xxxhdpi\编组 5.png" width="460" height="540" />
      <a-typography class="login">
        <div class="login-tab-box">
          <a-button class="login-tab" type="text" :class="{tabActive: formState.type === 1}" @click="loginTabClick('codeLogin')" >验证码登录</a-button>
          <a-button class="login-tab" type="text" :class="{tabActive: formState.type === 2}" @click="loginTabClick('passwordLogin')" >密码登录</a-button>
        </div>
          <a-form
            class="form"
            :model="formState"
            name="basic"
            :label-col="{ span: 0 }"
            :wrapper-col="{ span: 24 }"
            autocomplete="off"
            @submit="handleLogin"
          />
        <a-typography-paragraph>
          <a-form
            class="form"
            :model="formState"
            name="basic"
            :label-col="{ span: 0 }"
            :wrapper-col="{ span: 24 }"
            autocomplete="off"
            @submit="handleLogin"
          >
            <a-form-item name="phone" :rules="[{ required: true, message: `请输入${formState.type === 1 ? '手机号' : '账号'}!` },{ required: formState.type === 1 ?true:false,validator:accountValidate, message: '手机号码格式错误!' }]">
              <a-input v-model:value="formState.phone" placeholder="手机号" class="default-height">
                <template #prefix>
                  <img src="@\assets\xxxhdpi\name-icon.png" width="16" height="16" />
                </template>
              </a-input>
            </a-form-item>
            <a-form-item class="mb36" v-if="formState.type === 1" name="code" :rules="[{ required: true, message: '请输入验证码' }]">
              <a-input v-model:value="formState.code" placeholder="验证码" class="default-height" autocomplete="off" style="width: 228px">
                <template #prefix>
                  <img src="@\assets\xxxhdpi\code-icon.png" width="16" height="16" />
                </template>
              </a-input>
              <a-button class="getCode default-height" :disabled="codeState.codeDisabled" :class="{getCodeDisable:codeState.codeDisabled}" @click="getCode" >{{codeState.codeDisabled?'('+codeState.time+')':'获取验证码'}}</a-button>
            </a-form-item>
            

            <a-form-item class="mb36" v-if="formState.type === 2" name="password" :rules="[{ required: true, message: '请输入你的密码!' }]">
              <a-input-password v-model:value="formState.password" placeholder="密码" auto-complete="off" class="default-height">
                <template #prefix>
                  <img src="@\assets\xxxhdpi\passWord-icon.png" width="16" height="16" />
                </template>
              </a-input-password>
              
            </a-form-item>

            <a-form-item class="mb12">
              <a-button type="primary" html-type="submit" style="width: 100%; height: 48px"
                >登录</a-button
              >
            </a-form-item>
            <a-form-item>
              <a-checkbox v-model:checked="isAgree">已阅读并同意  <span class="blue" @click="openAgreement(AGREEMENT_TYPE.用户协议)">《用户协议》</span>与<span class="blue" @click="openAgreement(AGREEMENT_TYPE.隐私政策)">《隐私政策》</span></a-checkbox>
            </a-form-item>
            <Agreement 
            :key="agreementType" v-model:visible="agreementVisible" :agreementType="agreementType"/>
            <div style="text-align: center;">
                <RouterLink to="/findPassword" class="back-login">找回密码</RouterLink>
              </div>
          </a-form>
        </a-typography-paragraph>
      </a-typography>
    </div>
  </div>  
</template>
<script lang="ts" setup>
import { login } from '@/api/user'
import { useUserInfoStore } from '@/stores/modules/userInfo'
import { inject, reactive, ref, h } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getSmsCode } from '@/api/user'
import { message } from 'ant-design-vue'
import type { LoginForm } from '@/api/type'
import { AGREEMENT_TYPE } from '@/const'

// @todo 处于登录情况下，跳转回首页

interface CodeState {
  time: number
  codeDisabled: boolean
}
const formState = reactive<LoginForm>({
  phone: '',
  password: '',
  code: '',
  type: 1
})
const route = useRoute()
const router = useRouter()
const isAgree = ref<boolean>(false)
const codeState = reactive<CodeState>({
  time: 60,
  codeDisabled: false
})
const accountValidate = (rule: any, value: string) => {
  if (!value) {
    return Promise.reject('请输入账号')
  } else if (!/^[a-zA-Z0-9_-]{4,16}$/.test(value)) {
    return Promise.reject('请输入正确的账号')
  } else {
    return Promise.resolve()
  }
}
const userStore = useUserInfoStore()
let phoneValidate = (rule: any, value: string) => {
  if (!value) {
    return Promise.reject('请输入手机号')
  } else if (!/^1[3456789]\d{9}$/.test(value)) {
    return Promise.reject('请输入正确的手机号')
  } else {
    return Promise.resolve()
  }
}

const setIntervalValue= inject('setIntervalValue', () => {})
function handleLogin() {
  if(!isAgree.value){
    let errorOptions = {
            content: ()=>h('span',{style: {color:'#292929',marginLeft:'8px'}},['为了保护你的权益，请先阅读并同意我们的',h('span',{style: {color:'#3875F6'}},'用户协议')]),
            duration: 3,
            icon: ()=> h('img', { src: new URL('@/assets/xxxhdpi/error-icon.png', import.meta.url), width: 16, height: 16 }),
        }
        message.error(errorOptions)
    return
  }
  login(formState).then(async (res) => {
    console.log('res', res, res.data.entity)
    if (!res.data.ok) return
    userStore.setFrontToken(res.data.entity as unknown as string)
    setIntervalValue()
    await userStore.setUserInfo()
    // 根据是否 有redirect，跳转回去
    if(route.query?.redirect){
      router.push(route.query.redirect as string)
    }else{
      router.push({name: 'chatDefault'})
    }
  })
}
const getCode = async() =>{
  if(codeState.codeDisabled){
    return
  }
  try {
    await phoneValidate({},formState.phone)
    const {data} = await getSmsCode(formState.phone)
   if (!data.ok) return
   message.success('验证码发送成功')
    codeState.codeDisabled = true
    let timer = setInterval(() => {
      codeState.time--
      if (codeState.time <= 0) {
        clearInterval(timer)
        codeState.time = 60
        codeState.codeDisabled = false
      }
    }, 1000)
  } catch (error) {
    console.log(error)
    if(typeof error === 'string'){
      message.error(error)
    }
    
  }
}
const loginTabClick = (type: string) =>{
  if(type === 'codeLogin'){
    formState.type = 1
  }else{
    formState.type = 2
  }
}
const applyTest = () =>{
  router.push('/applyTest')
}

const agreementVisible = ref(false)
const agreementType = ref<AGREEMENT_TYPE>(AGREEMENT_TYPE.用户协议)
const openAgreement = (type: AGREEMENT_TYPE) => {
  agreementType.value = type
  agreementVisible.value = true
}
</script>

<style lang="scss" scoped>
  .home {
    display: grid;
    grid-template-columns: 1fr;
    margin: 0 auto;
    justify-items: center;
    position: relative;
    .applyTest{
      position: absolute;
      top: 40px;
      right: 40px;
      background: #3A76F6;
    }
  }
  .main {
    display: flex;
    flex-flow: row nowrap;
    border-radius: 16px;
    box-shadow: 0px 20px 40px 10px rgba(184, 198, 223, 0.1);
    margin-top: 18vh;
    .login-tab-box{
      display: flex;
      justify-content: space-between;
      width: 224px;
      height: 32px;
      border-radius:6px;
      border: 1px dashed #5c5e61;
      margin: auto;
      margin-bottom: 32px;
      .login-tab{
        width: 104px;
      }
      .tabActive{
        background: #2A8BF2;
        color: #fff;
        border-radius: 6px;
      }
    }
  }
  .login {
    width: 460px;
    background: white;
    box-sizing: border-box;
    padding: 124px 32px 32px;
    border-radius: 0 16px 16px 0;
    .default-height{
      height: 48px;
    }
    .getCode{
      float: right;
      background: #3C7BFF;
      color: #fff;
      width: 136px;
    }
    .getCodeDisable{
      background: #E5E5E5;
      color: #646464;
    }
  }
  .welcome-text {
    margin: 32px auto;
    font-size: 24px;
    font-weight: 600;
    line-height: 30px;
    text-align: center;
    color: #3a82ff;
  }
  .back-login{
    color: #646464;
  }

  .blue {
    cursor: pointer;
    color: #3875f6;
  }
  .mb36 {
    margin-bottom: 36px;
  }
  .mb12 {
    margin-bottom: 12px;
  }
</style>
